package com.fbt.transfer.app.driver.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.TextView;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.fbt.transfer.app.driver.http.ApiClient;
import com.fbt.transfer.app.driver.http.ApiInterface;
import com.fbt.transfer.app.driver.util.DialogUtils;
import com.fbt.transfer.app.driver.util.NotificationUtils;
import com.fbt.transfer.app.driver.R;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author tuocoo
 */
public abstract class BaseActivity extends AppCompatActivity {

  private boolean showBackButton = false;
  private final List<ActionButton> actionButtons = new ArrayList<>();
  private View customTitleView = null;
  private boolean isTitleCentered = false;
  private int titleTextColor = R.color.white;
  private int titleBackgroundColor = R.color.colorPrimary;
  private float titleTextSize = 18f;
  private int titlePadding = 16;
  private boolean isTitleBarElevated = false;
  private float titleBarElevation = 4f;
  private int titleBarHeight = 56;
  private boolean isTitleBarTransparent = false;
  protected ApiInterface apiInterface = null;
  protected Dialog loadingDialog = null;
  private static final CopyOnWriteArrayList<BaseActivity> ALL_ACTIVITIES = new CopyOnWriteArrayList<>();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ALL_ACTIVITIES.add(this);
    setupActionBar();
    apiInterface = ApiClient.getApiInterface();
    loadingDialog = DialogUtils.createLoadingDialog(this, true);
    // 初始化视图
    initView();
    // 初始化监听器
    initListener();
    // 初始化数据
    initData();
  }

  private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayShowTitleEnabled(true);
      actionBar.setDisplayShowCustomEnabled(true);
      actionBar.setDisplayUseLogoEnabled(false);
      actionBar.setDisplayShowHomeEnabled(false);

      // 设置标题栏背景色
      updateTitleBarBackground();

      // 设置标题文字颜色
      if (customTitleView != null) {
        TextView titleText = customTitleView.findViewById(R.id.title_text);
        if (titleText != null) {
          titleText.setTextColor(ContextCompat.getColor(this, titleTextColor));
        }
      }

      // 设置标题栏高度
      updateTitleBarElevation();

      // 设置标题栏内边距
      actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
    }
  }

  /**
   * 设置标题栏是否透明
   *
   * @param transparent 是否透明
   */
  protected void setTitleBarTransparent(boolean transparent) {
    isTitleBarTransparent = transparent;
    updateTitleBarBackground();
  }

  /**
   * 设置标题栏阴影
   *
   * @param elevated 是否显示阴影
   */
  protected void setTitleBarElevated(boolean elevated) {
    isTitleBarElevated = elevated;
    updateTitleBarElevation();
  }

  /**
   * 设置标题栏阴影高度
   *
   * @param elevation 阴影高度
   */
  protected void setTitleBarElevation(float elevation) {
    titleBarElevation = elevation;
    updateTitleBarElevation();
  }

  /**
   * 设置标题栏高度
   *
   * @param height 高度
   */
  protected void setTitleBarHeight(int height) {
    titleBarHeight = height;
    if (customTitleView != null) {
      ViewGroup.LayoutParams params = customTitleView.getLayoutParams();
      params.height = height;
      customTitleView.setLayoutParams(params);
    }
  }

  private void updateTitleBarBackground() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      if (isTitleBarTransparent) {
        actionBar.setBackgroundDrawable(null);
      } else {
        actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, titleBackgroundColor));
      }
    }
  }

  private void updateTitleBarElevation() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      actionBar.setElevation(isTitleBarElevated ? titleBarElevation : 0);
    }
  }

  /**
   * 设置标题栏渐变背景
   *
   * @param startColor 开始颜色
   * @param endColor   结束颜色
   */
  protected void setTitleBarGradientBackground(int startColor, int endColor) {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      GradientDrawable gradientDrawable = new GradientDrawable(
          GradientDrawable.Orientation.LEFT_RIGHT,
          new int[]{startColor, endColor}
      );
      actionBar.setBackgroundDrawable(gradientDrawable);
    }
  }

  /**
   * 设置标题栏动画
   *
   * @param show 是否显示
   */
  protected void animateTitleBar(boolean show) {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      View titleBar = actionBar.getCustomView();
      if (titleBar != null) {
        float startY = show ? -titleBarHeight : 0;
        float endY = show ? 0 : -titleBarHeight;

        ObjectAnimator animator = ObjectAnimator.ofFloat(titleBar, "translationY", startY, endY);
        animator.setDuration(300);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
      }
    }
  }

  /**
   * 设置标题文字动画
   *
   * @param text 新文本
   */
  protected void animateTitleText(String text) {
    if (customTitleView != null) {
      TextView titleText = customTitleView.findViewById(R.id.title_text);
      if (titleText != null) {
        // 淡出动画
        ObjectAnimator fadeOut = ObjectAnimator.ofFloat(titleText, "alpha", 1f, 0f);
        fadeOut.setDuration(150);
        fadeOut.addListener(new AnimatorListenerAdapter() {
          @Override
          public void onAnimationEnd(Animator animation) {
            titleText.setText(text);
            // 淡入动画
            ObjectAnimator fadeIn = ObjectAnimator.ofFloat(titleText, "alpha", 0f, 1f);
            fadeIn.setDuration(150);
            fadeIn.start();
          }
        });
        fadeOut.start();
      }
    }
  }

  /**
   * 设置操作按钮动画
   *
   * @param buttonId 按钮ID
   * @param show     是否显示
   */
  protected void animateActionButton(int buttonId, boolean show) {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      View buttonView = actionBar.getCustomView();
      if (buttonView != null) {
        float startAlpha = show ? 0f : 1f;
        float endAlpha = show ? 1f : 0f;

        ObjectAnimator animator = ObjectAnimator.ofFloat(buttonView, "alpha", startAlpha, endAlpha);
        animator.setDuration(300);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
      }
    }
  }
  /**
   * 初始化视图
   */
  protected abstract void initView();
  /**
   * 初始化数据
   */
  protected void initData() {
  }
  /**
   * 初始化监听器
   */
  protected void  initListener(){}

  /**
   * 设置标题
   *
   * @param title 标题文本
   */
  protected void setTitle(String title,boolean centered) {
    ActionBar actionBar = getSupportActionBar();
    isTitleCentered = centered;
    if (actionBar != null) {
      if (isTitleCentered) {
        setupCenteredTitle(title);
      } else {
        actionBar.setTitle(title);
      }
    }
  }

  /**
   * 设置标题居中
   *
   * @param centered 是否居中
   */
  protected void setTitleCentered(boolean centered) {
    isTitleCentered = centered;
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null && actionBar.getTitle() != null) {
      setTitle(actionBar.getTitle().toString());
    }
  }

  /**
   * 设置标题文字颜色
   *
   * @param colorResId 颜色资源ID
   */
  protected void setTitleTextColor(int colorResId) {
    titleTextColor = colorResId;
    if (customTitleView != null) {
      TextView titleText = customTitleView.findViewById(R.id.title_text);
      if (titleText != null) {
        titleText.setTextColor(ContextCompat.getColor(this, colorResId));
      }
    }
  }

  /**
   * 设置标题栏背景颜色
   *
   * @param colorResId 颜色资源ID
   */
  protected void setTitleBackgroundColor(int colorResId) {
    titleBackgroundColor = colorResId;
    updateTitleBarBackground();
  }

  /**
   * 设置标题文字大小
   *
   * @param size 文字大小
   */
  protected void setTitleTextSize(float size) {
    titleTextSize = size;
    if (customTitleView != null) {
      TextView titleText = customTitleView.findViewById(R.id.title_text);
      if (titleText != null) {
        titleText.setTextSize(size);
      }
    }
  }

  /**
   * 设置标题内边距
   *
   * @param padding 内边距
   */
  protected void setTitlePadding(int padding) {
    titlePadding = padding;
    if (customTitleView != null) {
      customTitleView.setPadding(padding, 0, padding, 0);
    }
  }

  private void setupCenteredTitle(String title) {
    if (customTitleView == null) {
      customTitleView = getLayoutInflater().inflate(R.layout.layout_title_center, null);
      customTitleView.setPadding(titlePadding, 0, titlePadding, 0);
      ActionBar actionBar = getSupportActionBar();
      if (actionBar != null) {
        actionBar.setCustomView(customTitleView);
      }
    }

    TextView titleText = customTitleView.findViewById(R.id.title_text);
    if (titleText != null) {
      titleText.setText(title);
      titleText.setTextSize(titleTextSize);
      titleText.setTextColor(ContextCompat.getColor(this, titleTextColor));
    }
  }

  /**
   * 设置返回按钮
   *
   * @param show 是否显示返回按钮
   */
  protected void setDisplayHomeAsUpEnabled(boolean show) {
    showBackButton = show;
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(show);
      if (show) {
        actionBar.setHomeAsUpIndicator(ContextCompat.getDrawable(this, R.drawable.ic_back));
        actionBar.setHomeActionContentDescription(getString(R.string.back));
      }
    }
  }

  /**
   * 添加操作按钮
   *
   * @param icon     按钮图标资源ID
   * @param text     按钮文本
   * @param listener 点击监听器
   * @return 按钮ID
   */
  protected int addActionButton(int icon, String text, OnActionButtonClickListener listener) {
    int buttonId = R.id.action_button_start + actionButtons.size();
    actionButtons.add(new ActionButton(buttonId, icon, text, listener));
    invalidateOptionsMenu();
    return buttonId;
  }

  /**
   * 移除操作按钮
   *
   * @param buttonId 按钮ID
   */
  protected void removeActionButton(int buttonId) {
    actionButtons.removeIf(button -> button.id == buttonId);
    invalidateOptionsMenu();
  }

  /**
   * 清除所有操作按钮
   */
  protected void clearActionButtons() {
    actionButtons.clear();
    invalidateOptionsMenu();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    for (ActionButton button : actionButtons) {
      MenuItem menuItem = menu.add(Menu.NONE, button.id, Menu.NONE, button.text);
      if (button.icon != 0) {
        menuItem.setIcon(button.icon);
      }
      menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
      // 添加按钮点击动画
      menuItem.setActionView(new View(this));
      menuItem.getActionView().setOnClickListener(v -> {
        animateButtonClick(v);
        button.listener.onActionButtonClick();
      });
    }
    return true;
  }

  private void animateButtonClick(View view) {
    // 缩放动画
    ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.8f, 1f);
    ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.8f, 1f);

    // 旋转动画
    ObjectAnimator rotation = ObjectAnimator.ofFloat(view, "rotation", 0f, 360f);

    scaleX.setDuration(200);
    scaleY.setDuration(200);
    rotation.setDuration(300);

    scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
    scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
    rotation.setInterpolator(new AccelerateDecelerateInterpolator());

    scaleX.start();
    scaleY.start();
    rotation.start();
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
      onBackPressed();
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 获取所有活动实例
   */
  public static CopyOnWriteArrayList<BaseActivity> getAllActivities() {
    return ALL_ACTIVITIES;
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    // 移除当前活动
    ALL_ACTIVITIES.remove(this);
    NotificationUtils.release(this);
  }

  /**
   * 处理返回按钮点击
   */
  @Override
  public void onBackPressed() {
    super.onBackPressed();
    finish();
  }

  /**
   * 操作按钮点击监听器接口
   */
  public interface OnActionButtonClickListener {

    void onActionButtonClick();
  }

  /**
   * 操作按钮数据类
   */
  private static class ActionButton {

    final int id;
    final int icon;
    final String text;
    final OnActionButtonClickListener listener;

    ActionButton(int id, int icon, String text, OnActionButtonClickListener listener) {
      this.id = id;
      this.icon = icon;
      this.text = text;
      this.listener = listener;
    }
  }
} 
